

from datetime import datetime
import hashlib
import ipaddress
import random
import re
import string
from flask import request
import os
import time

def get_ip():
    # 尝试从X-Forwarded-For请求头中获取IP地址
    # 如果不存在，则回退到request.remote_addr
    ip_address = request.headers.get('X-Forwarded-For', request.remote_addr)
    # 如果X-Forwarded-For包含多个IP地址，取第一个即可
    if ',' in ip_address:
        ip_address = ip_address.split(',')[0]
    return ip_address

def is_valid_emails(emails):
    if type(emails) == str:
        emails = emails.split(',')
    for email in emails:
        if not is_string_valid(email):
            return False
        email = email.strip()
        if is_valid_email(email) is False:
            return False
    return True

def is_valid_email(email):
    # 定义邮箱格式的正则表达式
    email_regex = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
    # 使用正则表达式匹配
    return re.match(email_regex, email) is not None

def is_string_valid(s):
    return s is not None and s.strip() != ''

def get_time():
    return datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def parse_time(time_str, format='%Y-%m-%d %H:%M:%S'):
    return datetime.strptime(time_str, format)

# 指定秒数和连接符
def format_seconds(seconds, connector=''):
    # 计算年、月、日、小时、分钟、秒
    year_seconds = 365 * 24 * 3600
    month_seconds = 30 * 24 * 3600  # 假设每月30天

    years = seconds // year_seconds
    seconds %= year_seconds

    months = seconds // month_seconds
    seconds %= month_seconds

    days = seconds // 86400  # 1天 = 24小时 * 3600秒
    seconds %= 86400

    hours = seconds // 3600
    seconds %= 3600

    minutes = seconds // 60
    seconds %= 60

    # 根据计算结果构建时间字符串
    time_parts = []
    if years > 0:
        time_parts.append(f"{years}年")
    if months > 0:
        time_parts.append(f"{months}月")
    if days > 0:
        time_parts.append(f"{days}日")
    if hours > 0:
        time_parts.append(f"{hours}小时")
    if minutes > 0:
        time_parts.append(f"{minutes}分钟")
    if seconds > 0 or len(time_parts) == 0:  # 如果没有其他时间单位，至少显示秒数
        time_parts.append(f"{seconds}秒")

    return connector.join(time_parts)


def hash_message(message, secret):
    return hashlib.md5((message+secret).encode('utf-8')).hexdigest()

def generate_random_string(length=16):
    # 定义可选字符集（字母和数字）
    characters = string.ascii_letters + string.digits
    # 使用random.choice从字符集中随机选择字符并组合成字符串
    random_string = ''.join(random.choice(characters) for _ in range(length))
    return random_string

def validate_client_id(s, length=16):
    # 检查字符串长度是否为16，且由大小写字母和数字组成
    if len(s) == length and re.fullmatch(r'[A-Za-z0-9]+', s):
        return True
    return False

# 将逗号分隔的端口字符串转换为 int 数组
def parse_ports(port_string):
    try:
        return [int(port.strip()) for port in port_string.split(",")]
    except ValueError as e:
        print(f"Invalid port string: {port_string}. Error: {e}")
        return []
    

def is_valid_ipv4(ip):
    try:
        ipaddress.IPv4Address(ip)
        return True
    except ipaddress.AddressValueError:
        return False
 
def is_valid_ipv6(ip):
    try:
        ipaddress.IPv6Address(ip)
        return True
    except ipaddress.AddressValueError:
        return False
 
def is_valid_domain(domain):
    # 定义域名的正则表达式（注意：这个正则表达式可能不是完美的，但它是一个起点）
    domain_pattern = re.compile(
        r'^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+(?:[A-Za-z]{2,}|xn--[A-Za-z0-9]+)\.?$'
    )
    
    # 检查域名是否匹配正则表达式
    return bool(domain_pattern.match(domain))
 
def is_valid_ip_or_domain(input_str):
    return is_valid_ipv4(input_str) or is_valid_ipv6(input_str) or is_valid_domain(input_str)



if __name__ == '__main__':
    print(format_seconds(163, ','))